package com.cn.ZhiKeDianShang.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.Oss.OssService;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseFragment;
import com.cn.ZhiKeDianShang.model.TaskInfoBean;
import com.cn.ZhiKeDianShang.model.event.sendImageBean;
import com.cn.ZhiKeDianShang.model.response.ImageBean;
import com.cn.ZhiKeDianShang.presenter.MineFragmentPresenter;
import com.cn.ZhiKeDianShang.presenter.view.MineFragmentView;
import com.cn.ZhiKeDianShang.ui.activity.OrderDetailActivity;
import com.cn.ZhiKeDianShang.ui.adapter.GridViewAdapter;
import com.cn.ZhiKeDianShang.util.ClipboardUtils;
import com.cn.ZhiKeDianShang.util.ImageGetterUtils;
import com.cn.ZhiKeDianShang.util.MultiImagePreview.AppConstant;
import com.cn.ZhiKeDianShang.util.MultiImagePreview.MultiImagePreviewActivity;
import com.cn.ZhiKeDianShang.util.Netdialog.StyledDialog;
import com.cn.ZhiKeDianShang.util.PrefShare;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.util.view.MyGridView;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 我的
 * Created by chengaofu on 2017/6/21.
 */

public class OrderDetailsFragment extends BaseFragment<MineFragmentView, MineFragmentPresenter> implements MineFragmentView {

    @BindView(R.id.grid_view)
    MyGridView gridView;
    @BindView(R.id.tv_dsptname)
    TextView tvDsptname;
    @BindView(R.id.tv_xdje)
    TextView tvXdje;
    @BindView(R.id.tv_shoptitle)
    TextView tvShoptitle;
    @BindView(R.id.tv_xsjg)
    TextView tvXsjg;
    @BindView(R.id.tv_keywords)
    TextView tvKeywords;
    @BindView(R.id.tv_link)
    TextView tvLink;
    @BindView(R.id.tv_spwa)
    TextView tvSpwa;
    @BindView(R.id.ll_spwa)
    RelativeLayout ll_spwa;


    @BindView(R.id.ll_yq)
    LinearLayout ll_yq;
    @BindView(R.id.tv_yq)
    TextView tvYq;
    @BindView(R.id.tv_xdxx)
    TextView tvXdxx;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_ordernumber)
    TextView tvOrdernumber;
    @BindView(R.id.et_ordernumbertv)
    EditText etOrdernumbertv;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.im_mainpicture)
    ImageView im_mainpicture;
    @BindView(R.id.im_ewm)
    ImageView im_ewm;


    Unbinder unbinder;

    private ProgressDialogFragment mProgressDialog;

    String orderId = "";
    String taskState = "";
    TaskInfoBean.OrderinfoBean orderinfoBean;
    //图片本地地址集合
    private ArrayList<ImageBean> mlocalPhotoList;
    private GridViewAdapter mAdapter;
    int sumNumber = 6;

    static OrderDetailActivity.showPhotoPop mShowPhotoPop;


    public static OrderDetailsFragment getInstance(String orderId, String taskState, TaskInfoBean.OrderinfoBean bean, OrderDetailActivity.showPhotoPop showPhotoPop) {
        mShowPhotoPop = showPhotoPop;
        OrderDetailsFragment fragment = new OrderDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("bean", bean);
        bundle.putString("taskState", taskState);
        bundle.putString("orderId", orderId);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Debug", "到达onCreate方法中----------------------");
        Bundle arguments = getArguments();
        orderId = arguments.getString("orderId");
        taskState = arguments.getString("taskState");
        orderinfoBean = (TaskInfoBean.OrderinfoBean) arguments.getSerializable("bean");
    }

    @Override
    protected void initViewsAndEvents() {
        Log.d("Debug", "到达initViewsAndEvents方法中");
        //初始化OssService类，参数分别是Content，accessKeyId，accessKeySecret，endpoint，bucketName（后4个参数是您自己阿里云Oss中参数）
        ossService = new OssService(getActivity(), accessKeyId, accessKeySecret, endpoint, bucketName);
        //初始化OSSClient
        ossService.initOSSClient();

        mlocalPhotoList = new ArrayList<>();
        mAdapter = new GridViewAdapter(getActivity(), mlocalPhotoList, sumNumber, taskState, new GridViewAdapter.onGridViewAdapterClick() {
            @Override
            public void onItemClick(int position) {
                int viewType = mAdapter.getItemViewType(position);
                if (viewType == 1) {
                    //弹起选择 相机还是相册
                    if (!taskState.equals("4")) {
                        mShowPhotoPop.showPhotoPop(orderId, sumNumber - mlocalPhotoList.size());
                    }
                } else {
                    //查看图片
                    ArrayList<String> imageList = new ArrayList<>();
                    for (int i = 0; i < mlocalPhotoList.size(); i++) {
                        imageList.add(mlocalPhotoList.get(i).getOssUrl());
                    }
                    Intent intent = new Intent(getActivity(), MultiImagePreviewActivity.class);
                    intent.putExtra(AppConstant.EXTRA_IMAGES, imageList);
                    intent.putExtra(AppConstant.EXTRA_POSITION, position);
                    intent.putExtra(AppConstant.EXTRA_CHANGE_SELECTED, false);
                    startActivity(intent);
                }
            }

            @Override
            public void delete(int position) {
                //上传到cos地址拼接
                StringBuilder deletest = new StringBuilder();
                for (int i = 0; i < mlocalPhotoList.size(); i++) {
                    ImageBean imageBean = mlocalPhotoList.get(i);
                    if (i != position) {
                        if (i == mlocalPhotoList.size() - 1) {
                            deletest.append(imageBean.getOssUrl());
                        } else {
                            deletest.append(imageBean.getOssUrl() + ",");
                        }
                    }

                }
                Log.d("Debug", "删除之后上传的地址" + deletest.toString());
                updateTaskinfo(deletest.toString() + "", 1, position);
            }
        });
        gridView.setAdapter(mAdapter);

        if (orderinfoBean != null) {
            initView();
        }

    }


    /**
     * @param type 0是添加   1是删除  2是更改实际支付金额  3.更改订单编号  4是修改备注
     */
    private void updateTaskinfo(String message, int type, int position) {
        String token = PrefShare.getInstance(getActivity()).getString("token");
        String userId = PrefShare.getInstance(getActivity()).getString("userId");
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        params.put("token", token);
        params.put("userid", userId);
        params.put("orderid", orderinfoBean.getId() + "");
        switch (type) {
            case 0:
                params.put("photos", message);
                break;
            case 1:
                params.put("photos", message);
                break;
            case 2:
                params.put("pay", message);
                break;
            case 3:
                params.put("ordernum", message);
                break;
            case 4:
                params.put("remark", message);
                break;
        }

        HttpUtils.post().url(AppConfig.ORDER_UPDATEOEDERINFO)
                .params(params)
                .build()
                .execute(new BaseCallback<TaskInfoBean>(TaskInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TaskInfoBean> result) {
                        try{
                            Log.d("Debug", "上传成功之后时间" + System.currentTimeMillis());
//                        DialogHelper.dismissProgressDialog();
                            Log.d("Debug", "到达请求这里---");
                            if (Result.checkSuccess(getActivity(), result)) {
                                switch (type) {
                                    case 0:
                                        orderinfoBean.setPhotos(message);
                                        break;
                                    case 1:
                                        mlocalPhotoList.remove(position);
                                        mAdapter.notifyDataSetChanged();
                                        ToastUtil.showShort("删除成功");
                                        orderinfoBean.setPhotos(message);
                                        break;
                                    case 2:
                                        orderinfoBean.setPay(message);
                                        break;
                                    case 3:
                                        orderinfoBean.setOrdernum(message);
                                        break;
                                    case 4:
                                        orderinfoBean.setRemark(message);
                                        break;
                                }
//                            KeyBoardUtil.hindKeyBoard(getActivity());
                            }
                            StyledDialog.dismiss(gloablDialog);
                        }catch (Exception E){

                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                        StyledDialog.dismiss(gloablDialog);
                    }
                });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        if (!isVisibleToUser){
//            KeyBoardUtil.hindKeyBoard(getActivity());
//        }
    }

    /**
     * 界面赋值
     */
    public void initView() {
        tvDsptname.setText("电商平台：" + orderinfoBean.getDsptname() + "");
        tvXdje.setText(orderinfoBean.getXdje() + "");
        tvShoptitle.setText("店铺名称：" + orderinfoBean.getShoptitle() + "");
        tvXsjg.setText(orderinfoBean.getXsjg() + "");


        if (TextUtils.isEmpty(orderinfoBean.getKeywords())) {
            tvKeywords.setVisibility(View.GONE);
        } else {
            tvKeywords.setVisibility(View.VISIBLE);
            tvKeywords.setText(orderinfoBean.getKeywords() + "");
        }


        if (TextUtils.isEmpty(orderinfoBean.getLink())) {
            tvLink.setVisibility(View.GONE);
        } else {
            tvLink.setVisibility(View.VISIBLE);
            tvLink.setText(orderinfoBean.getLink() + "");
        }


//        //加载路径
//        bv_img.setImage(BIG_IMAGE_PAHT);
//        //加载 InputStream
//        bv_img.setImage(InputStream is)
//        //加载网络图片 callBack : 加载中的回调
//        bv_img.setNetUrl(orderinfoBean.getLink(), new LoadNetImageCallBack() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void onLoadSucceed() {
//
//            }
//
//            @Override
//            public void onLoadFail(Exception e) {
//
//            }
//
//            @Override
//            public void onLoadProgress(int progress) {
//
//            }
//        });


        if (TextUtils.isEmpty(orderinfoBean.getSpwa())) {
            ll_spwa.setVisibility(View.GONE);
        } else {
            ll_spwa.setVisibility(View.VISIBLE);
            tvSpwa.setText(Html.fromHtml(orderinfoBean.getSpwa(), new ImageGetterUtils.MyImageGetter(getActivity(), tvSpwa), null));
            Log.d("Debug", "接口中返回商品简介为---" + orderinfoBean.getSpwa());
        }


        if (TextUtils.isEmpty(orderinfoBean.getYq())) {
            ll_yq.setVisibility(View.GONE);
        } else {
            ll_yq.setVisibility(View.VISIBLE);
            tvYq.setText(Html.fromHtml(orderinfoBean.getYq(), new ImageGetterUtils.MyImageGetter(getActivity(), tvYq), null));
        }


        if (TextUtils.isEmpty(orderinfoBean.getXdxx())) {
            tvXdxx.setVisibility(View.GONE);
        } else {
            tvXdxx.setVisibility(View.VISIBLE);
            tvXdxx.setText("下单选项：" + orderinfoBean.getXdxx() + "");
        }


        if (TextUtils.isEmpty(orderinfoBean.getMainpicture())) {
            im_mainpicture.setVisibility(View.GONE);
        } else {
            im_mainpicture.setVisibility(View.VISIBLE);
            Glide.with(getActivity())
                    .load(orderinfoBean.getMainpicture())
                    .into(im_mainpicture);
        }
        if (TextUtils.isEmpty(orderinfoBean.getEwm())) {
            im_ewm.setVisibility(View.GONE);
        } else {
            im_ewm.setVisibility(View.VISIBLE);
            Glide.with(getActivity())
                    .load(orderinfoBean.getEwm())
                    .into(im_ewm);
        }


        if (taskState.equals("4")) {
            etRemark.setEnabled(false);
            etMoney.setEnabled(false);
            etOrdernumbertv.setEnabled(false);
        } else {
            etRemark.setEnabled(true);
            etMoney.setEnabled(true);
            etOrdernumbertv.setEnabled(true);
        }

        if (!TextUtils.isEmpty(orderinfoBean.getPay())) {
            etMoney.setText(orderinfoBean.getPay());
        }
//        etMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                Log.d("Debug", "etMoney focus 离开了界面");
//                if (etMoney != null) {
//                    updateTaskinfo(etMoney.getText().toString(), 2, 0);
//                }
//            }
//        });
//

        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun2 != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler2.removeCallbacks(delayRun2);
                }
                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler2.postDelayed(delayRun2, 800);
            }
        });


        if (!TextUtils.isEmpty(orderinfoBean.getOrdernum())) {
            etOrdernumbertv.setText(orderinfoBean.getOrdernum());
        }

//        etOrdernumbertv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                Log.d("Debug", "etOrdernumbertv focus 离开了界面");
//                if (etOrdernumbertv != null) {
//                    updateTaskinfo(etOrdernumbertv.getText().toString(), 3, 0);
//                }
//            }
//        });

        etOrdernumbertv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(delayRun);
                }
                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler.postDelayed(delayRun, 800);
            }
        });


        if (!TextUtils.isEmpty(orderinfoBean.getRemark()) || !orderinfoBean.getRemark().equals("0")) {
            etRemark.setText(orderinfoBean.getRemark());
        }
//        etRemark.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                Log.d("Debug", "etRemark focus 离开了界面");
//                if (etRemark != null) {
//                    updateTaskinfo(etRemark.getText().toString(), 4, 0);
//                }
//            }
//        });


        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun1 != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler1.removeCallbacks(delayRun1);
                }
                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler1.postDelayed(delayRun1, 800);
            }
        });


        if (!TextUtils.isEmpty(orderinfoBean.getPhotos())) {
            if (orderinfoBean.getPhotos().contains(",")) {
                String[] split = orderinfoBean.getPhotos().split(",");
                for (int i = 0; i < split.length; i++) {
                    mlocalPhotoList.add(new ImageBean(split[i], ""));
                }
            } else {
                mlocalPhotoList.add(new ImageBean(orderinfoBean.getPhotos(), ""));
            }
            mAdapter.notifyDataSetChanged();
        }


    }


    private Handler handler = new Handler();
    private Handler handler1 = new Handler();
    private Handler handler2 = new Handler();

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            if (etOrdernumbertv != null) {
                updateTaskinfo(etOrdernumbertv.getText().toString(), 3, 0);
            }
        }
    };
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun1 = new Runnable() {

        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            if (etRemark != null) {
                updateTaskinfo(etRemark.getText().toString(), 4, 0);
            }
        }
    };
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun2 = new Runnable() {

        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            if (etMoney != null) {
                updateTaskinfo(etMoney.getText().toString(), 2, 0);
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        Log.d("OrderDetailsFragment","onResume中--------------------");
    }


    @Override
    public void onPause() {
        super.onPause();
//        Log.d("Debug","onPause()---------");
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.ordetail_layout;
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.ordetail_layout;
    }

    @Override
    protected MineFragmentPresenter createPresenter() {
        return new MineFragmentPresenter(getContext(), this);
    }


    @Override
    public void requestFailed(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }


    //----------------------------下面是上传oss 的操作------------------------------------------

    //上传的进度回调
    String accessKeyId = "LTAI4FpBbo7yfZx1waLnveHQ";
    String accessKeySecret = "aymEw4VmeHKuFtnyYVoyDIziQrCLff";
    String endpoint = "http://cdnzkds.zyfjsm.com";
    String bucketName = "gpos-zkds";
    OssService ossService;
    Dialog gloablDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(sendImageBean messageEvent) {
        //
        if (orderId == messageEvent.getOrderId()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ArrayList<String> localList = new ArrayList<>();
                    for (int i = 0; i < messageEvent.getImages().size(); i++) {
                        mlocalPhotoList.add(new ImageBean(messageEvent.getImages().get(i)));
                        mAdapter.notifyDataSetChanged();
                        localList.add(messageEvent.getImages().get(i));
                    }
                    gloablDialog = StyledDialog.buildLoading(getActivity(), "上传中...").show();

                    Log.d("Debug", "上传前计时" + System.currentTimeMillis());
                    ossService.ossUploadBefore(getActivity(), orderinfoBean.getId() + "", localList, new ArrayList<>(), new OssService.SomeOnUploadListener() {
                        @Override
                        public void onSuccess(List<ImageBean> ossUrls) {
                            Log.d("Debug", "到达上传图片成功这里---------------" + ossUrls.size());
                            //根据本地地址   赋值oss地址
                            for (int i = 0; i < mlocalPhotoList.size(); i++) {
                                for (int j = 0; j < ossUrls.size(); j++) {
                                    if (mlocalPhotoList.get(i).getLocalUrl().equals(ossUrls.get(j).getLocalUrl())) {
                                        mlocalPhotoList.get(i).setOssUrl(ossUrls.get(j).getOssUrl());
                                    }
                                }
                            }
                            //这里拼接上传地址
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < mlocalPhotoList.size(); i++) {
                                String ossUrl = mlocalPhotoList.get(i).getOssUrl();
                                if (i == mlocalPhotoList.size() - 1) {
                                    sb.append(ossUrl);
                                } else {
                                    sb.append(ossUrl).append(",");
                                }
                            }

                            updateTaskinfo(sb.toString(), 0, 0);
                            Log.d("ossUploadBefore", "要上传的oss地址" + sb.toString());
                        }
                    });
                }
            });
        }

    }

    @OnClick({R.id.tv_keywords, R.id.tv_link, R.id.tv_spwa})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_keywords:
                ClipboardUtils.setClipboard(getActivity(), tvKeywords.getText().toString(), "关键词复制成功");
                break;
            case R.id.tv_link:
                Log.d("Debug", "商品链接复制成功");
                ClipboardUtils.setClipboard(getActivity(), tvLink.getText().toString(), "商品链接复制成功");
                break;
            case R.id.tv_spwa:
                Log.d("Debug", "商品文案复制成功");
                ClipboardUtils.setClipboard(getActivity(), tvSpwa.getText().toString(), "商品文案复制成功");
                break;
        }
    }
}